<?php

define("DB_HOST" , "192.168.1.2");
define("DB_USER" , "root");
define("DB_PASS" , "deep1234");
define("DB_NAME" , "filebin");


$f = new filebin();

class filebin{
	public $transferKEY = "dfasdfasdfasdfag45tyw45yuw57uje56uw4r5h76e57j76jk78k89l6089l90p79";
	public $HTTPSERVER = "http://localhost/gtk/filebinrepos/httpserver/incoming.php";
	public $URL = "http://localhost/gtk/filebinrepos/httpserver/";
	public $load_at_once = 100;
	public $local_big_thumb_size = 350;
	public $max_file_size= 90000000;
	


/*
//Mysql settings
define("DB_HOST" , "ownalbum.com");
define("DB_USER" , "ownalbum_filebin");
define("DB_PASS" , "uv.qMZjM7xsp");
define("DB_NAME" , "ownalbum_filebin");



$f = new filebin();

class filebin{
	public $HTTPSERVER = "http://www.ownalbum.com/incoming.php";
	public $URL = "http://www.ownalbum.com/";
	public $load_at_once = 100;
	public $local_big_thumb_size = 350;
	public $max_file_size= 90000000;
	public $transferKEY = "dfasdfasdfasdfag45tyw45yuw57uje56uw4r5h76e57j76jk78k89l6089l90p79";

*/
	











































	//PLEASE DO NOT EDIT BELOW THIS LINE UNLESS YOU ARE REALLY SURE OF WHAT YOU'RE DOING...
	public $windows = array(
					"main"=>"main" , 
					"dberror"=>"dberror", 
					"login"=>"login",
					"album_select"=>"album_select",
					"tag"=>"tag"
					);
	public $files_model;
	public $files_view;
	public $selection;
	public $filePath;
	public $uploadURL;
	public $formFileVariableName;
	public $postParams = array();
	public $ch;
	public $file;
	public $size;
	public $dialog;
	public $idle_ID;
	public $on = 0;
	public $progress_bar;
	public $error_dialog;
	public $filecode;
	public $downloadURLDialog;
	public $username; //The user username that is currently logged in
	public $uid; //The user ID that is currently logged in
	public $password; //The user password that is currently logged in
	public $username_text;
	public $password_text;
	public $album;
	public $tags = array(); //Some picture tags that are being set
	public $status = array(); //Either picture is private or public
	public $albums_combobox; //The Album selection combo-box object
	public $albums_model; //The Album selection combo-box model object
	public $album_text; //The Album name GtkEntry object
	public $file_thumb_queue;
	public $proc_file_idle_id;
	public $progress_thumbs;
	public $this_file_thumb;
	public $min_task = 0;
	public $overall_status = "public";
	public $overall_tags = array();
	public $public_status;
	public $private_status;
	public $tagEntry;
	public $progress_tags;
	public $min_tags_process = 0;
	public $min_remove = 0;
	public $load_all_check;
	public $pages_combo;
	public $pages_mdoel;
	public $file_upload_progress;
	
	
	public function __construct(){
		$this->login_wnd();
		Gtk::main();
	}
	
	
	
	public function perform_login(){
		$this->username = $this->username_text->get_text();
		$this->password = $this->password_text->get_text();
		
		$conn = $this->mysql_conn();
		if(!$conn){
			$this->error_dialog("Database connection problem","Database error. Please try again later." , "290");
		}else{
			$loc = new Local();
			$sel = mysql_query("select * from filebin_users where 
								user_name='".$loc->db_cmp($this->username)."' and pass_word='".$loc->db_cmp($this->password)."'"
							  );
			$res = mysql_fetch_array($sel);
			mysql_free_result($sel);
			mysql_close();
			if($res['id']){
			
				unset($this->username);
				unset($this->password);
				$this->username=$res['user_name'];
				$this->password=$res['pass_word'];
				$this->uid=$res['id'];
				$this->album="album";
				
				$this->windows['login']->destroy();//Close login
				
				$this->album_select_wnd();//Open main window
				Gtk::main();//Reiterate GtkMAIN
			}else{
				unset($this->username);
				unset($this->password);
				$this->username_text->set_text("");
				$this->password_text->set_text("");
				$this->error_dialog("Invalid Login","Invalid Login. Please try again.","202");
			}
		}
	}
	
	public function album_select_wnd(){
		
		$this->windows['album_select'] = new GtkWindow();
		$this->windows['album_select']->set_title("Hello ".$this->username."-> Select album...");
		$this->windows['album_select']->set_icon_from_file("images/chat.png");
		//$this->windows['album_select']->set_size_request(410, 90);
		//$this->windows['album_select']->set_position(Gtk::WIN_POS_CENTER);
		$this->windows['album_select']->connect_simple('destroy', array('Gtk','main_quit'));
		
		$albumTbl = new GtkTable();
		$pleaseLabel = $this->make_label("Which album will you be managing today ?" , "Tahoma" , "13" , "#330000");
		
		$this->display_albums_combo();
		
		$albumGoButton = $this->create_img_button("Continue >>", "images/album.png", "continue_to_selected_album", "Tahoma", "9", "#339900", "22","22", "120", "32" , "horizontal");
		$albumNoGoButton = $this->create_img_button("", "images/quit.png", "reopen_login_from_album_select", "Tahoma", "9", "#339900", "16","16", "28", "26" , "horizontal");
		
		
		$this->load_all_check = new GtkCheckButton("Also load remote file-info for file-management. Images preview will NOT be available...");

		$albumTbl->attach($pleaseLabel , 0,3,0,1 , Gtk::FILL, Gtk::SHRINK);
		$albumTbl->attach($this->albums_combobox ,0,1,1,2 , Gtk::FILL, Gtk::SHRINK);
		$albumTbl->attach($albumGoButton ,1,2,1,2 , Gtk::FILL, Gtk::SHRINK);
		
		$albumTbl->attach($albumNoGoButton ,2,3,1,2 , Gtk::FILL, Gtk::SHRINK);
		
		$albumTbl->attach($this->load_all_check ,0,3,2,3 , Gtk::FILL, Gtk::SHRINK);
		
		$this->windows['album_select']->add($albumTbl);
		$this->windows['album_select']->show_all();
	}
	
	public function display_albums_combo(){
		// Create a combobox
		$this->albums_combobox = new GtkComboBox();
		
		// Create a model
		if (defined("GObject::TYPE_STRING")) {
		    $this->albums_model = new GtkListStore(GObject::TYPE_STRING);
		} else {
		    $this->albums_model = new GtkListStore(Gtk::TYPE_STRING);
		}
		
		// Set up the combobox
		$this->albums_combobox->set_model($this->albums_model);
		$cellRenderer = new GtkCellRendererText();
		$this->albums_combobox->pack_start($cellRenderer);
		$this->albums_combobox->set_attributes($cellRenderer, 'text', 0);
		
		// Stuff the choices in the model
		//Add the option to create a new album first
		$this->albums_model->append(array("==CREATE NEW ALBUM=="));
		//Now make the database connection to grab existing albums
		$conn = $this->mysql_conn();
		if(!$conn){
			$this->error_dialog("Database connection problem","Database error. Please try again later." , "290");
		}else{
			$loc = new Local();
			$sel = mysql_query("select DISTINCT(album) as albums from filebin_files where uid='".$this->uid."' order by album asc");
			while($res = mysql_fetch_array($sel)){
				$this->albums_model->append(array($loc->db_out($res['albums'])));
			}
			mysql_free_result($sel); mysql_close();
		}
	}
	
	public function continue_to_selected_album(){
		$this->album = $this->albums_model->get_value($this->albums_combobox->get_active_iter(), 0);
		//echo $this->album;
		if(strlen($this->album) > 0){
			$this->windows['album_select']->destroy();
			$this->windows['login']->destroy();
			$this->main_wnd();
			if($this->load_all_check->get_active() == true && $this->album != "==CREATE NEW ALBUM=="){
				$this->populate_with_db_records();
			}
			Gtk::main();//Reiterate GtkMAIN
		}
	}
	
	public function reopen_login_from_album_select(){
		unset($this->username);
		unset($this->password);
		unset($this->uid);
		$this->windows['album_select']->destroy();
		$this->login_wnd();
		Gtk::main();
	}
	
	
	
	public function login_wnd(){
		
				
		$this->windows['login'] = new GtkWindow();
		$this->windows['login']->set_title("Login to album");
		//$this->windows['login']->set_size_request(310, 140);
		//$this->windows['login']->set_position(Gtk::WIN_POS_CENTER);	
		$this->windows['login']->connect_simple('destroy', array('Gtk','main_quit'));
		$this->windows['login']->set_icon_from_file("images/chat.png");
		
		$loginTbl = new GtkTable();
		
		//Create the login image
		$loginImage = $this->image("images/enter.png" , "45" , "45");
		
		//Username and password labels
		$usernameLabel = $this->make_label("Username:" , "Tahoma" , "10" , "#330000");
		$passwordLabel = $this->make_label("Password:" , "Tahoma" , "10" , "#330000");
		
		//Forgot Password Link Label
		$forgotLabel = $this->make_link("Forgot Password?", $this->URL . "forgot.php");
		
		//Register Account Link Label
		$registerLabel = $this->make_link("Register New Account", $this->URL . "register.php");
		
		// Create the username and password text fields.
		$this->username_text   = new GtkEntry(); $this->password_text   = new GtkEntry(); $this->password_text->set_visibility(false);
		
		$this->username_text->set_text("ciprian");
		$this->password_text->set_text("deep1234");
		//Login Button
		$login = $this->create_img_button("Continue Login", "images/login.png", "perform_login", "Tahoma", "9", "#339900", "32","32", "80", "42" , "horizontal");
		$quit = $this->create_img_button("Quit", "images/quit.png", "close_application", "Tahoma", "9", "#FF0000", "32","32", "80", "42", "horizontal");
		
		$loginTbl->attach($loginImage , 0,1,0,2 , Gtk::SHRINK, Gtk::SHRINK);
		
		$loginTbl->attach($usernameLabel , 1 , 2 , 0 , 1 , Gtk::SHRINK, Gtk::SHRINK);
		$loginTbl->attach($passwordLabel , 1 , 2 , 1 , 2 , Gtk::SHRINK, Gtk::SHRINK);
		
		$loginTbl->attach($this->username_text , 2 , 3 , 0 , 1 , Gtk::FILL, Gtk::FILL);
		$loginTbl->attach($this->password_text , 2 , 3 , 1 , 2 , Gtk::FILL, Gtk::FILL);
		
		$loginTbl->attach($quit , 1 , 2 , 2 , 3 , Gtk::FILL, Gtk::FILL);
		$loginTbl->attach($login , 2 , 3 , 2 , 3 , Gtk::FILL, Gtk::FILL);
		
		$loginTbl->attach($forgotLabel , 1 , 2 , 3 , 4 , Gtk::FILL, Gtk::FILL);
		$loginTbl->attach($registerLabel , 2 , 3 , 3 , 4 , Gtk::FILL, Gtk::FILL);
		
		$this->windows['login']->add($loginTbl);
		$this->windows['login']->show_all();
		
	}
	
	public function close_application(){
		Gtk::main_quit();
		exit;
	}	
	
	public function main_wnd(){
		$this->windows['main'] = new GtkWindow();
		$this->windows['main']->set_title("File and Image sharing and storage facility");
		$this->windows['main']->set_size_request(750, 490);
		$this->windows['main']->set_icon_from_file("images/chat.png");
		//$this->windows['main']->set_position(Gtk::WIN_POS_CENTER);	
		$this->windows['main']->connect_simple('destroy', array('Gtk','main_quit'));
		$this->windows['main']->drag_dest_set(Gtk::DEST_DEFAULT_ALL, array(array( 'text/uri-list', 0, 0)), Gdk::ACTION_COPY);
		$this->windows['main']->connect('drag-data-received', array($this , 'on_drop'));
		
		//Create a Box and add it to window
		$tbl = new GtkTable();
		
		
		//Create a Label widget
		/*
		$title = new GtkLabel("Some shitty label");
		$title->modify_font(new PangoFontDescription("Verdana 10"));
		$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#339900"));
		
		//Put the title label widget in the box
		$this->box[0]->put($title, 10, 10);
		*/
		$btnHBox = new GtkHBox();
		//Create process selection buttons with scaled images
		$upload = $this->create_img_button("Upload Selected", "images/upload.png", "on_button_process", "Tahoma", "9", "#339900", "32","32", "120", "75" , "vertical");
		$remove = $this->create_img_button("Delete Selected", "images/delete.png", "remove_selected", "Tahoma", "9", "red", "32","32", "120", "75" , "vertical");
		$tag = $this->create_img_button("Tag Selected", "images/tag.png", "tag_selected", "Tahoma", "9", "#339900", "32","32", "120", "75" , "vertical");
		$changeAlbum = $this->create_img_button("Change Album", "images/album.png", "change_album", "Tahoma", "9", "#339900", "32","32", "120", "75" , "vertical");
		$logoutButton = $this->create_img_button("Logout", "images/quit.png", "reopen_login_from_main", "Tahoma", "9", "#339900", "32","32", "120", "75" , "vertical");
		$removeAlbum = $this->create_img_button("Delete Album", "images/delete_album.png", "delete_album", "Tahoma", "9", "red", "32","32", "120", "75" , "vertical");
		$btnHBox->add($upload);
		$btnHBox->add($tag);
		$btnHBox->add($remove);
		$btnHBox->add($changeAlbum);
		$btnHBox->add($removeAlbum);
		$btnHBox->add($logoutButton);
	
		$tbl->attach($btnHBox , 0,3,0,1, Gtk::SHRINK, Gtk::SHRINK);
		
		$vbox = new GtkVBox();
		$maxSize = number_format(round($this->max_file_size/1024));
		
		$this->errLbl = new GtkLabel("Please drag and drop your files here. Max file size: ".$maxSize." Kb.");
		$this->errLbl->modify_font(new PangoFontDescription("Verdana 10"));
		$this->errLbl->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#FF0000"));
		$tbl->attach($this->errLbl , 0,3,1,2, Gtk::FILL, Gtk::FILL);
		
		if($this->album != "==CREATE NEW ALBUM=="){
			$sessionLbl = $this->make_link("CLICK HERE TO VIEW YOUR ALBUM: ".strtoupper($this->album), $this->URL."view_album.php?album=".$this->album);
			$tbl->attach($sessionLbl , 0,3,2,3, Gtk::SHRINK, Gtk::SHRINK);
		}else{
			//Define a GtkEntry for the new albun name
			$this->album_text = new GtkEntry();
			$this->album_text->set_width_chars(50);
			
			$tbl->attach($this->album_text , 1,2,2,3, Gtk::SHRINK, Gtk::SHRINK);
			//Define a Label for this bullshit
			$albumEntryLabel = new GtkLabel("Please Name Your New Album: ");
			$albumEntryLabel->modify_font(new PangoFontDescription("Tahoma 12"));
			$albumEntryLabel->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#330000"));
			$tbl->attach($albumEntryLabel , 0,1,2,3, Gtk::SHRINK, Gtk::SHRINK);
			//Button to view the album
			$albumViewButton = $this->create_img_button("View Album", "images/album.png", "view_album", "Tahoma", "9", "#339900", "32","32", "130", "28" , "horizontal");
			$tbl->attach($albumViewButton , 2,3,2,3, Gtk::SHRINK, Gtk::SHRINK);
		}
		
		if($this->load_all_check->get_active() == true && $this->album != "==CREATE NEW ALBUM=="){
			$nxHBox = new GtkHBox();
			$pagesLbl = new GtkLabel("Album Pages: ");
			$pagesLbl->modify_font(new PangoFontDescription("Tahoma 12"));
			$pagesLbl->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#330000"));
			
			$this->pages_combo = new GtkComboBox();
			// Create a model
			if (defined("GObject::TYPE_STRING")) {
			    $this->pages_model = new GtkListStore(GObject::TYPE_STRING);
			} else {
			    $this->pages_model = new GtkListStore(Gtk::TYPE_STRING);
			}
			
			// Set up the combobox
			$this->pages_combo->set_model($this->pages_model);
			$cellRenderer = new GtkCellRendererText();
			$this->pages_combo->pack_start($cellRenderer);
			$this->pages_combo->set_attributes($cellRenderer, 'text', 0);
			
			// Stuff the choices in the model
			$conn = $this->mysql_conn();
			if(!$conn){
				$this->error_dialog("Database connection problem" , "Database error. Please try again later." , "290");
			}else{
				$loc = new Local();
				$num_pages = ceil(mysql_num_rows(mysql_query("select id from filebin_files where album='".$loc->db_cmp($this->album)."'"))/$this->load_at_once);
				mysql_close();
			}
			$num_display = $num_pages + 1;
			for($pag = 1 ; $pag < $num_display ; $pag++){
				$this->pages_model->append(array($pag));
			}
			$this->pages_combo->set_active(0);
			
			$this->pages_combo->connect_simple('changed' , array($this , 'turn_the_page_metallica'));
			
			$nxHBox->pack_start( $pagesLbl , false, false);
			$nxHBox->pack_start( $this->pages_combo , false, false);
			
			$vbox->pack_start($nxHBox,false,false);
		}
		
		$this->display_table($vbox, $files);
		
		$this->file_upload_progress = new GtkProgressBar();
        $this->file_upload_progress->set_orientation(Gtk::PROGRESS_LEFT_TO_RIGHT);
        
        $tbl->attach($this->file_upload_progress , 0,3,4,5 , Gtk::FILL, Gtk::SHRINK);
        
		$tbl->attach($vbox , 0,3,3,4);
		
		//Nice try... but it takes forever and let's just give Caesar (the Web) what belongs to the Web...
		//$this->populate_with_db_records();
		

		$this->windows['main']->add($tbl);
		
		
		if(!$this->overall_status){ $this->overall_status = "public"; }
		//Show windnow and all widgets in it.
		$this->windows['main']->show_all();
	}
	
	public function delete_album(){
		$dest_remove_url = $this->URL . "remove_album.php?transferKEY=" . $this->transferKEY .
		        	 "&album=" . $this->album . "&username=" . $this->username . "&password=" . $this->password;
		
		$dest_remove_url = str_replace(" " , "%20" , $dest_remove_url);
		
		$fp = fopen($dest_remove_url , "r");
		fclose($fp );
		
		$this->change_album();
	}
	
	public function turn_the_page_metallica(){
		if($this->pages_combo->get_active_iter() > -1){
			$active_selection = $this->pages_model->get_value($this->pages_combo->get_active_iter(), 0);
			$active_selection = $active_selection-1;
			$next_iteration = $active_selection * $this->load_at_once;
			$this->populate_with_db_records($next_iteration);
		}		
	}
	
	public function tag_selected(){
		
		$this->windows['tag'] = new GtkWindow();
		$this->windows['tag']->set_icon_from_file("images/chat.png");
		$this->windows['tag']->set_position(Gtk::WIN_POS_CENTER);
		$this->windows['tag']->set_title('Set Files Tags');
		$this->windows['tag']->set_modal('true');
		$this->windows['tag']->connect_simple('destroy', array($this,'destroy_tags_window'));
		//$this->windows['tag']->set_size_request(450,120);
		
		$this->public_status  = $this->setup_radio(null, 'Make Selected Files Public', 'public');
		$this->private_status = $this->setup_radio($this->public_status, 'Make Selected Files Private', 'private');
		
		$tagsNoGoButton = $this->create_img_button("", "images/quit.png", "destroy_tags_window", "Tahoma", "9", "#339900", "16","16", "28", "28" , "horizontal");
		
		$labelTags = new GtkLabel("Enter your tags: ");
		$labelTags->modify_font(new PangoFontDescription("Tahoma 12"));
		$labelTags->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#330000"));
		
		$this->tagEntry = new GtkEntry();
		$this->tagEntry->set_width_chars(50);
		
		$saveTagsButton = $this->create_img_button("Save", "images/save.png", "save_tags", "Tahoma", "9", "#339900", "16","16", "130", "28" , "horizontal");
		
		
		
		$tbl = new GtkTable();
		$hbox1 = new GtkHBox();
		$hbox2 = new GtkHBox();
		
		$hbox1->pack_start($this->public_status , false , false);
		$hbox1->pack_start($this->private_status , false , false);
		
		$hbox2->pack_start($this->tagEntry , false,false);
		$hbox2->pack_start($saveTagsButton , false,false);
		$hbox2->pack_start($tagsNoGoButton , false,false);
		
		
		$tbl->attach($hbox1 , 0 , 1 , 0 , 1 , Gtk::SHRINK , Gtk::SHRINK);
		$tbl->attach($labelTags , 0  ,1 , 1  ,2);
		$tbl->attach($hbox2 , 0 , 1 , 2 , 3 , Gtk::SHRINK , Gtk::SHRINK);
		
		$this->windows['tag']->add($tbl);
		$this->windows['tag']->show_all();
	}
	
	
	// function to simplify the display of grouped radio buttons
	public function setup_radio($radio_button_grp, $button_label, $button_value) {
	    $radio = new GtkRadioButton($radio_button_grp, $button_label);
	    $radio->connect('toggled', array($this , "on_toggle_status_radio"), $button_value);
	    return $radio;
	}
	
	// call-back function when user pressed a radio button
	public function on_toggle_status_radio($radio, $value) {
		
	    $label = $radio->child->get_label();
	    $active = $radio->get_active();
	    if($active){
	    	$this->overall_status = $value;
	    }
		//echo $this->overall_status;
	}
	
	public function save_tags(){
		
		$this->overall_tags = $this->tagEntry->get_text();
		$this->on_toggle_status_radio($this->public_status, "public");
		
		//print_r($this->overall_status);

		$selected_rows = $this->files_view->get_selected_items();

	    $i = 0;
	    //$j=0; foreach($slected_rows as $test){$j = $j+1;}
	    $max = count($this->files_view->get_selected_items());
	    //echo $max;
	    if(is_array($selected_rows) && $max>0){
	    	
		    foreach($selected_rows as $path) {
		        $iter = $this->files_model->get_iter($path);
		        ++$i;
		        $forFisier = $this->files_model->get_value($iter, 0);
		        
		        $this->tags[$forFisier] = $this->overall_tags;
		        $this->status[$forFisier] = $this->overall_status;
		        
		        //echo $this->tags[$forFisier]."\n";
		        		        
		        $filenameArr = explode("?filecode=" , $forFisier);
		        $filecode_remove = $filenameArr[1];
		        $filecodeArr = explode("&type=" , $filecode_remove );
		        $filecode_update  = $filecodeArr[0];
		        
		        
		        if(strlen($filecode_update) > 2){
		        	
		        	$dest_update_tags_url = $this->URL . "update_status.php?transferKEY=" . $this->transferKEY . "&filecode=" . $filecode_update . 
		        							"&username=" . $this->username . "&password=" . $this->password . "&status=" . 
		        							$this->status[$forFisier] . "&tags=" . $this->tags[$forFisier];
		        	$dest_update_tags_url = str_replace(" " , "%20" , $dest_update_tags_url);
		        	$fp = fopen($dest_update_tags_url , "r");
		        	$contBack = fread($fp , 3024);
		        	fclose($fp);

					//echo $contBack;
		        	
		        }
		       
		        
		        ++$this->min_tags_process;
			    $perc = round((100*$this->min_tags_process)/$max,2);
				$percDoWork = $perc/100;
				
		        $this->file_upload_progress->set_fraction($percDoWork);
		        $this->file_upload_progress->set_text($this->min_tags_process.' of '.$max.' files processed...');
		        
				while (Gtk::events_pending()) { Gtk::main_iteration(); }
			    /////
		    }
	    
	    
			if ($this->min_tags_process < $max) { // task completed?
	            return true; // not yet!
	        } else {
	        	unset($this->min_tags_process);
	            $this->windows['tag']->destroy();
	            return false;
	        }
	    }
	}
	
	public function on_delete_tags_me_event(){
		unset($this->min_tags_process);
		$this->progress_tags->destroy();
		$this->windows['tag']->destroy();
	}
	
	public function destroy_tags_window(){
		$this->windows['tag']->destroy();
	}
	
	
	public function reopen_login_from_main(){
		unset($this->username);
		unset($this->password);
		unset($this->uid);
		$this->windows['main']->destroy();
		$this->login_wnd();
		Gtk::main();
	}
	
	public function view_album(){
		$this->album = $this->album_text->get_text();
		if(strlen($this->album) > 0){
			$this->album_text->set_property('editable' , false);
			$this->link_clicked($a , $b , $this->URL . "view_album.php?album=" . $this->album);
		}else{
			$this->album = "==CREATE NEW ALBUM==";
			$this->error_dialog("Please enter album name" , "Album name is empty." , "160");
		}
	}
	
	public function change_album(){
		$this->windows['main']->destroy();
		$this->album_select_wnd();
		Gtk::main();
	}
	
	public function error_dialog($error_title,$error_text,$width){
		$clear = $this->create_img_button($error_text, "images/quit.png", "close_dberror", "Tahoma", "9", "#FF0033", "16","16", $width,"32", "horizontal");
		$this->windows['dberror'] = new GtkDialog($error_title , null, Gtk::DIALOG_MODAL);
		$this->windows['dberror']->set_position(Gtk::WIN_POS_CENTER);
	    $top_area = $this->windows['dberror']->vbox;
        $top_area->pack_start($clear);
        $this->windows['dberror']->set_has_separator(false);
        $this->windows['dberror']->show_all();
        $this->windows['dberror']->connect('delete-event', array($this, "delete_error_dialog")); 
	}
	
	public function delete_error_dialog(){
		$this->windows['dberror']->destroy();
	}
	
	public function mysql_conn(){
		//The mysql shit... May be used somewhere else in some other method though...
		$loc = new Local();
		if(!$loc->init_db(DB_HOST , DB_USER , DB_PASS)){
			return false;
		}else{
			if(!$loc->use_db(DB_NAME)){
				return false;
			}else{
				return true;
			}
		}
		//End the MySQL shit
	}
	
	
	public function download_file($widget, $event){
		if ($event->type==Gdk::_2BUTTON_PRESS) {
			$selected_rows = $this->files_view->get_selected_items();
		    $i = 0;
		    if(is_array($selected_rows)){
			    foreach($selected_rows as $path) {
			        $iter = $this->files_model->get_iter($path);
			        ++$i;
			        $forFisier = $this->files_model->get_value($iter, 0);
			    }
		    }
		    
		    $is_there = strpos($forFisier , "http://");
		    if($is_there !== false){
		    	$forFisier .="&sub_type=desktop";
				$shell = new COM('WScript.Shell');
				$shell->Run('cmd /c start "" "'.$forFisier.'"', 0, FALSE);
		    }else{
		    	$nameOfFileArr = explode("\\",$forFisier);
				$nameOfFile = $nameOfFileArr[count($nameOfFileArr)-1];
				$this->downloadURLDialog = new GtkDialog('Preview: '.$nameOfFile , null); // create a new dialog
				$this->downloadURLDialog->set_icon_from_file("images/chat.png");
				$this->downloadURLDialog->set_position(Gtk::WIN_POS_CENTER);
		        $top_area = $this->downloadURLDialog->vbox;
		        
	        	$imagePreview = $this->url_image($forFisier, $this->local_big_thumb_size);
	        	
				$top_area->pack_start($imagePreview,true,true);
		        $this->downloadURLDialog->set_has_separator(false);
		        $this->downloadURLDialog->show_all();
		        $this->downloadURLDialog->connect('delete-event', array($this, "destroy_downloadurl"));
		    }
	    }
	}
	
	public function destroy_downloadurl(){
		$this->downloadURLDialog->destroy();
	}
	
	
	
	
	public function view_sessions(){
		$shell = new COM('WScript.Shell');
        $shell->Run('cmd /c start "" "sessions.txt"', 0, FALSE);
	}
	
	
	public function make_link($title, $url) {
	    $label = new GtkLabel($title);
	    $label->set_markup('<span color="blue"><u>'.$title."</u></span>");
	    $eventbox = new GtkEventBox; // note 2
	    $eventbox->add($label);
	    $eventbox->set_visible_window(false);
	    $eventbox->connect('button-press-event', array($this,'link_clicked') , $url);
	    return $eventbox;
	}
	
	
	public function link_clicked($sender,$moreSender , $url){
		$shell = new COM('WScript.Shell');
        $shell->Run('cmd /c start "" "'.$url.'"', 0, FALSE);
	}
	
	
	public function make_label($text , $font , $font_size , $color){
		$label = new GtkLabel($text);
		$label->modify_font(new PangoFontDescription($font." ".$font_size));
		$label->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse($color));
		return $label;
	}
	public function close_dberror(){
		$this->windows['dberror']->destroy();

	}



	public function remove_selected($button){
		$selected_rows = $this->files_view->get_selected_items();
	    $i = 0;
	    $rows_to_remove = array(); 
	    $max = count($this->files_view->get_selected_items());
	    if(is_array($selected_rows) && $max > 0){
	    
	    
	    	//$this->progress_remove();
	    	
	    	
		    foreach($selected_rows as $path) {
		    	$rows_to_remove[] = $path[0];
		        $iter = $this->files_model->get_iter($path);
		        
		        //Remove file physically from server if it exists in there
		        $filename = $this->files_model->get_value($iter, 0);
		        
		        unset($this->tags[$filename]);
		        unset($this->status[$filename]);
		        
		        $filenameArr = explode("?filecode=" , $filename);
		        $filecode_remove = $filenameArr[1];
		        $filecodeArr = explode("&type=" , $filecode_remove );
		        $filecode_remove_send  = $filecodeArr[0];
		        //echo $filename;
		        if(strpos($filename , "http://") !== false && strlen($filecode_remove) > 2){

		        	$dest_remove_url = $this->URL . "remove_file.php?transferKEY=" . $this->transferKEY .
		        	 "&filecode=" . $filecode_remove_send . "&username=" . $this->username . "&password=" . $this->password;
		        	$dest_remove_url = str_replace(" " , "%20" , $dest_remove_url);
		        	//echo $dest_remove_url."\n\n";
		        	$fp = fopen($dest_remove_url , "r");
		        	//$contBack = fread($fp , 3024);
		        	//echo $contBack;
		        	fclose($fp);
					
		        	if(is_file("temp/" . $filecode_remove_send . ".jpg")){
		        		unlink("temp/" . $filecode_remove_send . ".jpg");
		        	}
		        }
		        
		        ++$i;
		   		++$this->min_remove;
			    $perc = round((100*$this->min_remove)/$max,2);
				$percDoWork = $perc/100;
				
		        $this->file_upload_progress->set_fraction($percDoWork);
		        $this->file_upload_progress->set_text($this->min_remove.' of '.$max.' files removed...');
		        
				while (Gtk::events_pending()) { Gtk::main_iteration(); }

		    }
				
		    //Removing from model now.
	    	for ($i=0; $i<count($rows_to_remove); $i++) {
	        	unset($this->files_model[$rows_to_remove[$i]]);
	     	}
	     	
	   		if ($this->min_remove < $max) { // task completed?
	            return true; // not yet!
	        } else {
	        	unset($this->min_remove);
	        	if($this->pages_combo && $this->pages_model){
	            	$this->update_pages();
	        	}
	            return false;
	        }
	    }
	}
	
	public function update_pages(){
		if($this->pages_combo){
			$was_active = $this->pages_combo->get_active();
			if($was_active == 0){$was_active = 1;}
			
			$this->pages_combo->set_active(-1);
			//update the pages number too.
	        $this->pages_model->clear();
	        $this->pages_combo->set_active(-1);
			// Now put back the correct pages
			$conn = $this->mysql_conn();
			if(!$conn){
				$this->error_dialog("Database connection problem" , "Database error. Please try again later." , "290");
			}else{
				$loc = new Local();
				$num_pages = ceil(mysql_num_rows(mysql_query("select id from filebin_files where album='".$loc->db_cmp($this->album)."'"))/$this->load_at_once);
				mysql_close();
			}
			$num_display = $num_pages + 1;
			for($pag = 1 ; $pag < $num_display ; $pag++){
				$this->pages_model->append(array($pag));
			}
			$this->pages_combo->set_active($was_active-1);
		}
	}


	public function create_img_button($label, $img, $callback, $font_name, $font_size, $color, $width, $height, $sizew, $sizeh, $position) { 
		$button = new GtkButton(); // create a standard button
		$button->set_size_request($sizew, $sizeh);
		$button->connect('clicked', array($this , $callback));
		if($position == "horizontal"){$button_hbox = new GtkHBox();}else{$button_hbox = new GtkVBox();}
		$button->add($button_hbox);
		$imag = new GtkImage();
		$imge=GdkPixbuf::new_from_file($img)->scale_simple($width, $height, Gdk::INTERP_HYPER);
		$imag->set_from_pixbuf($imge);
		$button_hbox->pack_start($imag, 0, 0);
		$button_hbox->pack_start(new GtkLabel(), 0, 0); // THIS IS A FUCKING SPACER
		$btnLabel = new GtkLabel($label);
		$btnLabel->modify_font(new PangoFontDescription("{$font_name} {$font_size}"));
		$btnLabel->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse($color));
		$button_hbox->pack_start($btnLabel, 0, 0);

		return $button;
	}
	
	public function image($path , $width, $height){
		$imag = new GtkImage();
		$imge=GdkPixbuf::new_from_file($path)->scale_simple($width, $height, Gdk::INTERP_HYPER);
		$imag->set_from_pixbuf($imge);
		return $imag;
	}
	
	public function display_table($vbox, $data) {

		// Set up a scroll window
		$scrolled_win = new GtkScrolledWindow();
		$scrolled_win->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
		$vbox->pack_start($scrolled_win ,true,true,3);

		// creates the list store
		if (defined("GObject::TYPE_STRING")) {
			$this->files_model = new GtkListStore(GObject::TYPE_STRING, GObject::TYPE_STRING, GdkPixbuf::gtype, GObject::TYPE_STRING);
		} else {
			$this->files_model = new GtkListStore(Gtk::TYPE_STRING, Gtk::TYPE_STRING, GdkPixbuf::gtype, Gtk::TYPE_STRING);
		}

		// creates the view to display the list store
		$this->files_view = new GtkIconView($this->files_model);
		$this->files_view->set_selection_mode(Gtk::SELECTION_MULTIPLE);
		//$this->files_view->set_columns(0);
		$this->files_view->set_text_column(1);
		$this->files_view->set_pixbuf_column(2);
		$this->files_view->set_item_width(120); 
		$this->files_view->connect('button-press-event', array($this, 'download_file'));
		
		$scrolled_win->add($this->files_view);


		
	}
	
	public function url_image($rim, $sz){
		$imgDat = @getimagesize($rim);
		$mime = $imgDat['mime'];
		$mimeArr = explode("/" , $mime);
		if($imgDat && $mimeArr[0] == "image" && $mime != "image/psd"){
		
			$imgDat = @getimagesize($rim);
			if($imgDat[0] > $sz || $imgDat[1] > $sz){
				$pixbuf = GdkPixbuf::new_from_file($rim);
			
				$MAX_IMG_WIDTH = $sz;
				$width = $pixbuf->get_width(); // note 2
		    	$height = $pixbuf->get_height(); 
		    	
		    	if ($width>MAX_IMG_WIDTH) {
					$new_width = $MAX_IMG_WIDTH;
			        $new_height = $MAX_IMG_WIDTH * $height / $width; 
		    	}
				$pixbuf = $pixbuf->scale_simple($new_width , $new_height,  Gdk::INTERP_HYPER);
			}else{
				$pixbuf = GdkPixbuf::new_from_file($rim);
			}
		}else{
			$pixbuf = GdkPixbuf::new_from_file("images/application.png");
		}
		
		$img = new GtkImage();
		$img -> set_from_pixbuf($pixbuf);
		
		return $img;
	}
	
	public function gd_pixbuf_thumb($rim , $sz){
	
		
		$imgDat = getimagesize($rim);
		$mime = $imgDat['mime'];
		
		$mimeArr = explode("/" , $mime);
		if($imgDat && $mimeArr[0] == "image" && $mime != "image/psd" && $imgDat != false){
		   
			$pixbuf = GdkPixbuf::new_from_file($rim);
			
			if($sz > -1){
				$MAX_IMG_WIDTH = $sz;
				$width = $pixbuf->get_width();
		    	$height = $pixbuf->get_height(); 
		    	
		    	if ($width>$MAX_IMG_WIDTH) {
					$new_width = $MAX_IMG_WIDTH;
			        $new_height = $MAX_IMG_WIDTH * $height / $width; 
		    	}
				$pixbuf = $pixbuf->scale_simple($new_width , $new_height,  Gdk::INTERP_NEAREST);
			}
			
		}else{
			$pixbuf = GdkPixbuf::new_from_file("images/application.png");
		}
		
		return $pixbuf;
	}
	
	
	public function remote_pixbuf($rim){
		$imgDat = getimagesize($rim);
		$mime = $imgDat['mime'];
		
		$mimeArr = explode("/" , $mime);
		if($imgDat && $mimeArr[0] == "image" && $mime != "image/psd" && $imgDat != false){
		
			$rimArr = explode("?filecode=" , $rim);
			$rimPart = $rimArr[1];
			$rimPartArr = explode("&type=", $rimPart);
			$file_is_there = "temp/".$rimPartArr[0].".jpg";
			
			$pixbuf = GdkPixbuf::new_from_file($rim);
			return $pixbuf;
			
		}else{
			$pixbuf = GdkPixbuf::new_from_file($rim);
			return $pixbuf;
		}
	}
	

	public function populate_with_db_records($start = 0){
		//First remove all values no matter what
		$this->files_view->select_all();
		$selected_rows = $this->files_view->get_selected_items();
	    $i = 0;
	    $rows_to_remove = array(); 
	    $max = count($this->files_view->get_selected_items());
	    if(is_array($selected_rows) && $max > 0){
	    	foreach($selected_rows as $path) {
		    	$rows_to_remove[] = $path[0];
	    	}
	    }
		//Removing from model now.
    	for ($i=0; $i<count($rows_to_remove); $i++) {
        	unset($this->files_model[$rows_to_remove[$i]]);
     	}
	
		Gtk::idle_add(array($this , "get_remote_stack"),$start);
		
		$this->proc_file_idle_id = Gtk::idle_add(array($this , "process_remote_files"));
	}
	
	public function get_remote_stack($start){
			$urlSend = $this->URL . "serve_stack.php?username=".$this->username."&password=".$this->password."&album=".$this->album . 
			"&stack=".$this->load_at_once."&start=".$start;
			
			$urlSendTo = str_replace(" ","%20",$urlSend);
			$stack_return = file_get_contents($urlSendTo);
			
			$stack_return = trim($stack_return);
			
			$stack_returnArr = explode("," , $stack_return);
			foreach($stack_returnArr as $res){
				$resArr = explode("<|>" , $res);
				$this->file_thumb_queue[] = array("URL"=>$resArr[0], "filename"=>$resArr[1]);
			}
	}
	
	
	public function process_remote_files(){
		//Process long task
		$max = count($this->file_thumb_queue);
		//var_dump($this->file_thumb_queue);
		if(is_array($this->file_thumb_queue)){
			foreach($this->file_thumb_queue as $file_thumb){
				if(strlen($file_thumb['URL']) > 5 && strlen($file_thumb['filename']) > 0){
				
					$rimArr = explode("?filecode=" , $file_thumb['URL']);
					$rimPart = $rimArr[1];
					$rimPartArr = explode("&type=", $rimPart);
					$file_is_there = "temp/".$rimPartArr[0].".jpg";
					
					if(is_file($file_is_there)){
						$imageURL_use = $file_is_there;
					}else{
						if($rimPartArr[1] == "thumb"){
							/* Disable caching for now
							$cont = file_get_contents($file_thumb['URL']);
							$fp = fopen($file_is_there ,"w");
							fwrite($fp , $cont);
							fclose($fp);
							
							$imageURL_use = $file_is_there;
							*/
						
							$imageURL_use = "images/nocache.jpg";
						}else{
							$imageURL_use = "images/application.png";
						}
					}
					$inside = array(
									$file_thumb['URL'] , 
									$file_thumb['filename'], 
									$this->remote_pixbuf($imageURL_use),
									"uploaded"
							);
						
			        $this->files_model->append($inside);
					
						
				    ++$this->min_task;
				    $perc = round((100*$this->min_task)/$max,2);
					$percDoWork = $perc/100;
					
			        $this->file_upload_progress->set_fraction($percDoWork);
			        $this->file_upload_progress->set_text($this->min_task.' of '.$max.' files downloaded...');
			        
					while (Gtk::events_pending()) { Gtk::main_iteration(); }
			}else{
				$this->min_task = $max; 
			}
		}
	   
		if ($this->min_task < $max) { // task completed?
            return true; // not yet!
        } else {
        	unset($this->min_task);
        	unset($this->file_thumb_queue);
        	Gtk::idle_remove($this->proc_file_idle_id); // inform php-gtk that we're done/
            return false;
        }
		}
	}


	
	public function on_drop($widget, $context, $x, $y, $data, $info, $time) {
		unset($this->file_thumb_queue);
        $uri_list = $data->data;
      	$uri_list = explode("\n" , $uri_list);
      	$this->file_thumb_queue = array();
      	
      	foreach($uri_list as $uri) {
          $uri = urldecode($uri);
          $uri = str_replace("file:///" , "" , $uri);
          $uri = str_replace("/" , "\\" , $uri);
          $uri = str_replace("\n" , "" , $uri);
          $uri = str_replace("\r" , "" , $uri);
          $uri = trim($uri);
          $uri = urldecode($uri);
          $fPath=str_replace("\\","/",$uri);
          //echo $uri."\n";
          if(file_exists($uri) && is_file($uri)) {
	          $size = filesize($uri);
	          //echo filesize($uri);
	          $sizec = $size/1024;
	           
	           
	           $oo = true;
	           $n = $this->files_model->iter_n_children(NULL);
			   for ($i=0; $i<$n; ++$i) {
			        $iter = $this->files_model->get_iter($i);
			        
			        $filename = $this->files_model->get_value($iter, 0);
			        
			        if($uri != $filename){
			        	//echo "adaug ".$uri."\n";
			        	$oo = true;
			        }else{
			        	$i = $n;
			        	$oo = false;
			        }
			   }
			   if($oo == true){
		   		  if($size < $this->max_file_size){
		   		
		   			$this->file_thumb_queue[] = $uri;
		   			
		   		  }else{
		   			//$this->error_dialog($errorMessage);
		   		  }
		   		}
        	}
       	}
	    
		
		$this->proc_file_idle_id = Gtk::idle_add(array($this , "process_thumbnails"));

	}
	
	
	
	public function process_thumbnails(){
		//Process long task
		$max = count($this->file_thumb_queue);
		
		foreach($this->file_thumb_queue as $file_thumb){
			unset($this->this_file_thumb);
			$nameOfFileArr = explode("\\",$file_thumb);
	   		$nameOfFile = $nameOfFileArr[count($nameOfFileArr)-1];
	   		//echo "Processing file " . $nameOfFile.":";
	   		//echo ".";
	   		$this->this_file_thumb = $nameOfFile;
	   		
	   		$imgDat = @getimagesize($file_thumb);
			if($imgDat[0] > 120 || $imgDat[1] > 120){
				$szTH = 120;
			}else{
				$szTH = -1;
			}
	        $this->files_model->prepend(array(
				            $file_thumb , 
				            $nameOfFile,
				            $this->gd_pixbuf_thumb($file_thumb , $szTH ),
				            "not uploaded"
	            			));
	       
	   		
	   		//echo "\n";
				
		    ++$this->min_task;
		    $perc = round((100*$this->min_task)/$max,2);
			$percDoWork = $perc/100;
			
	        $this->file_upload_progress->set_fraction($percDoWork);
	        $this->file_upload_progress->set_text($this->min_task.' of '.$max.' files processed...');
	        
			while (Gtk::events_pending()) { Gtk::main_iteration(); }
	    }
	   
		if ($this->min_task < $max) { // task completed?
            return true; // not yet!
        } else {
        	unset($this->min_task);
        	unset($this->file_thumb_queue);
        	Gtk::idle_remove($this->proc_file_idle_id); // inform php-gtk that we're done
            return false;
        }
		
	    
		
	}
	
	public function on_delete_me_event(){
		unset($this->min_task);
		Gtk::idle_remove($this->proc_file_idle_id); // inform php-gtk that we're done
        $this->progress_thumbs->destroy(); // yes, all done. close the dialog
	}
	
	
	public function on_delete_error(){
		$this->error_dialog->destroy();
	}
    
    	
	public function on_button_process($button) {
		//echo $this->album;
		if($this->album == "==CREATE NEW ALBUM=="){
	        //Check if use entered his album name
	        if(strlen($this->album_text->get_text()) > 0){
	        	$this->album = $this->album_text->get_text();
	        }else{
	        	$this->album = "==CREATE NEW ALBUM==";
	        }
        }
        //echo $this->album_text->get_text();
		$selected_rows = $this->files_view->get_selected_items();
		if(strlen($this->album) > 0 && $this->album != "==CREATE NEW ALBUM=="){
		    if(is_array($selected_rows)){
			    foreach($selected_rows as $path) {
			    	
			        $iter = $this->files_model->get_iter($path);
			        
			        $filename = $this->files_model->get_value($iter, 0);
			        $uploaded = $this->files_model->get_value($iter, 3);
			     	
			        
			        if($uploaded == "not uploaded"){
				        $filecode = md5($filename.time().mt_rand());
				        $this->file = $filename;
				        $this->filecode = $filecode;

						$this->idle_ID = Gtk::idle_add(array($this, 'progress'));
						if($this->album_text){
				    		$this->album_text->set_property('editable',false);
						}
						//echo $this->tags[$filename].'\n'.$this->status[$filename].'\n\n';
						//print_r($this->tags);
						//print_r($this->status);
				        $this->CurlFileUploader($filename , $this->HTTPSERVER , 'fisier_incarcat', 
				        Array(
				        	'filecode' => $filecode, 
				        	'transferKEY' => $this->transferKEY, 
				        	'uid' => $this->uid, 
				       		'password' => $this->password, 
				       		'username' => $this->username, 
				        	'album' => $this->album,
				        	'tags' => $this->tags[$filename],
				        	'status' => $this->status[$filename]
				        	)
				        );
						$this->UploadFile();
			        }
				}
			}
		}else{
	    	$this->error_dialog("Please name your album.", "Album name may not be empty." , 250);
	    }
	}
	
	
	public function CurlFileUploader ($filePath, $uploadURL, $formFileVariableName, /* assosiative array */ $otherParams = false) {
		$this->filePath = $filePath;
		$this->uploadURL = $uploadURL;
		if(is_array($otherParams) && $otherParams != false) {
			foreach ($otherParams as $fieldName => $fieldValue) {
				$this->postParams[$fieldName] = $fieldValue;
			}
		}
		$this->postParams[$formFileVariableName] = "@".$filePath;
	}
	public function UploadFile () {
		//cURL start
   		$this->ch = curl_init();
   		curl_setopt($this->ch, CURLOPT_URL, $this->uploadURL );
   		curl_setopt($this->ch, CURLOPT_POST, 1);
   		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->postParams);
   		curl_setopt($this->ch, CURLOPT_NOPROGRESS, 0);
   		curl_setopt($this->ch, CURLOPT_PROGRESSFUNCTION, array($this, 'progress'));
   		
   		$postResult = curl_exec($this->ch);
   		//echo $postResult;
   		curl_close($this->ch);
	}
	
	public function thumb($rim , $sz , $dest , $quality = 25){
		$imgDat = getimagesize($rim);
		$mime = $imgDat['mime'];
		   
		if ($imgDat[0] > $imgDat[1]+20) {
		  $tw = $sz;
		  $th = $imgDat[1]/($imgDat[0]/$tw);
		} else {
		  $th = $sz;
		  $tw = $imgDat[0]/($imgDat[1]/$th);
		}
	
		if ($sz == "-1") {
			$imNew = ImageCreateTrueColor($imgDat[0], $imgDat[1]);
		}else{
			$imNew = ImageCreateTrueColor($tw, $th);
		}
		   
		if ($mime == 'image/gif') {
		  $imFile= ImageCreateFromGIF($rim);
		} else if ($mime == 'image/png') {
		  $imFile= ImageCreateFromPNG($rim);
		} else if ($mime == 'image/jpeg') {
		  $imFile= ImageCreateFromJpeg($rim);
		}
		  
		if ($sz == "-1") {
		  imagecopyresampled ($imNew, $imFile, 0, 0, 0, 0, $imgDat[0], $imgDat[1], $imgDat[0], $imgDat[1]);
		} else {
		  imagecopyresampled ($imNew, $imFile, 0, 0, 0, 0, $tw, $th, $imgDat[0], $imgDat[1]);
		}
	
		imagejpeg($imNew, $dest, $quality);
	
		imagedestroy($imNew);
	}
	
	
	public function progress($zero ,$unu , $doi , $trei){
		if($doi > 0){
			$done  = number_format(round($trei/1024,2));
			$total = number_format(round($doi/1024,2));
			
			$perc = round((100*$trei)/$doi,2);
			$percDoWork = $perc/100;
			
	        $this->file_upload_progress->set_fraction($percDoWork);
	        $nameOfFileArr = explode("\\",$this->file);
			$nameOfFile = $nameOfFileArr[count($nameOfFileArr)-1];
	        $this->file_upload_progress->set_text($nameOfFile . ": " . $done.' Kb of '.$total.' Kb Complete');
	        
	     	//echo $trei." == ".$doi."\n";
        
			while (Gtk::events_pending()) { Gtk::main_iteration(); }
		
		
			if ($trei < $doi) { // task completed?
		           return false; // not yet!
		    }else{ // task has completed
		    
			 //Update the uploaded path
	    	 $n = $this->files_model->iter_n_children(NULL);
			 for ($i=0; $i<$n; ++$i) {
			   $iter = $this->files_model->get_iter($i);
			        
			   $filename = $this->files_model->get_value($iter, 0);
			   if($filename == $this->file){
			      $this->files_model->set($iter, 0, $this->URL . "download.php?filecode=" . $this->filecode);
			      $this->files_model->set($iter, 3, "uploaded");
			    }
			 }
			 
			 
			/* Disable caching for now...
			$imgDat = @getimagesize($this->file);
		    if($imgDat[0] > 800 || $imgDat[1] > 800){
				$sz = 120;
			}else{
				$sz = -1;
			}
			if($imgDat != false){
				//Now save a thumbnail of this file locally for caching purposes IF the file is an image
				$this->thumb($this->file, $sz, "temp/".$this->filecode . ".jpg", 100);
			}
			*/
			 
			 
		    	//usleep(990000);
	           Gtk::idle_remove($this->idle_ID); // inform php-gtk that we're done
	           return true;
		   }
		   
		}
	}
	
	public function on_delete_event($widget, $event) {
        Gtk::idle_remove($this->idle_ID); // inform php-gtk that we're done
        // any other clean-up that you may want to do
        return true;
    }
}


































class eKonLib{

	public $sqlink = "";
	public $sqdb = "";
	public $db_err;
	
	public function __construct(){
		
	}

	public function init_db($host, $user, $pass){
		$this->sqlink = mysql_connect($host, $user, $pass);
		if(!mysql_error()){
			return $this->sqlink;
		}else{
			return false;
		}
	}

	public function use_db($db_name){
		$this->sqdb = mysql_select_db($db_name , $this->sqlink);
		return $this->sqdb;
	}

	public function br_out($var){
		$returned = stripslashes(nl2br(strip_tags($var)));
		return $returned;
	}

	public function db_in($var){
		$returned = strip_tags(mysql_real_escape_string($var));
		return $returned;
	}

	public function db_out($var){
		$returned = stripslashes(strip_tags(stripslashes($var)));
		return $returned;
	}

	public function db_cmp($var){
		$returned = mysql_real_escape_string(strip_tags($var));
		return $returned;
	}

	public function captcha($code){
		$largeur=98;
		$hauteur=25;
		$img = imagecreate($largeur, $hauteur) or die("Cannot Initialize new GD image stream");

		$bgc = imagecolorallocate($img, mt_rand(235,255), mt_rand(235,255), mt_rand(235,255));
		$black = imagecolorallocate($img, 0, 0, 0);

		imagefilledrectangle($img, 0, 0, $largeur, $hauteur, $bgc);

		$hor_pos=mt_rand(5,15); // horizontal position
		for($i=0;$i<strlen($code);$i++){
			imagestring($img, 5, $hor_pos, mt_rand(2,10), $code[$i], $black);
			$hor_pos+=mt_rand(10,20);
		}

		for($i=0;$i<70;$i++){
			imagesetpixel($img, mt_rand(0,$largeur), mt_rand(0,$hauteur), imagecolorallocate($img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)));
		}

		for($i=0;$i<1;$i++){
			if($i<2){
				$x1=rand(0,$largeur);
				$y1=0;
				$x2=abs($x1-mt_rand(0,5));
				$y2=$hauteur;
			}else{
				$x1=0;
				$y1=rand(0,$hauteur);
				$x2=$largeur;
				$y2=abs($y1-mt_rand(0,5));
			}
			imageline($img, $x1, $y1, $x2, $y2, $black);
		}


		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
		header("Cache-Control: no-store, no-cache, must-revalidate"); 
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");
		header("Content-Type: image/png");
		imagePNG($img);
		imagedestroy($img);
	}

}

class Local extends eKonLib{
	public $limit;
	public $tax;

	public function is_duplicate($username){
		
		
		$sel = mysql_query("SELECT user_ID FROM users WHERE user_username = '" . $this->db_cmp($username) . "'");
		$res = mysql_fetch_array($sel);
		if($res['user_ID']){
			return true;
		}else{
			return false;
		}
		

	}



	public function is_captcha($code){
		
		
		if($code == $_SESSION['code']){
			return true;
		}else{
			return false;
		}
		

	}


	public function is_logged(){
		if($_SESSION['uid']){
			return true;
		}else{
			return false;
		}
	}

	public function check_session($err_url){
		if(!$_SESSION['uid']){
			echo "<script> alert('Your session has expired. Please login.'); location.href='" . $err_url . "'; </script>";
			exit;
		}
	}



	public function date_to_timestamp($date){

		$dateArr = explode("/" , $date);
		$month = $dateArr[0];
		$day   = $dateArr[1];
		$year  = $dateArr[2];

		$ret = @mktime(0 , 0 , 0 , $month , $day , $year);

		return $ret;
	

	}

	public function age($date){

		$dateArr = explode("/" , $date);
		$year  = $dateArr[2];

		$age = date("Y" , time()) - $year;

		return $age;
	

	}


	public function create_account(
		$user_username , 
		$user_password , 
		$user_name , 
		$user_email , 
		$user_phone , 
		$user_address , 
		$user_city , 
		$user_state , 
		$user_zip , 
		$user_country , 
		$user_email_code , 
		$user_birthdate){

		
		$birth_date = $this->date_to_timestamp($user_birthdate);
		
		
		mysql_query("INSERT INTO users (
		user_username,
		user_password,
		user_name,
		user_email,
		user_phone,
		user_address,
		user_city,
		user_state,
		user_zip,
		user_country,
		user_email_code,
		user_ip,
		user_date,
		user_status,
		user_paper_status,
		user_insurance_status,
		user_birthdate
		) VALUES (
		'" . $this->db_in($user_username) . "',
		'" . $this->db_in($user_password) . "',
		'" . $this->db_in($user_name) . "',
		'" . $this->db_in($user_email) . "',
		'" . $this->db_in($user_phone) . "',
		'" . $this->db_in($user_address) . "',
		'" . $this->db_in($user_city) . "',
		'" . $this->db_in($user_state) . "',
		'" . $this->db_in($user_zip) . "',
		'" . $this->db_in($user_country) . "',
		'" . $user_email_code . "',
		'" . $_SERVER['REMOTE_ADDR'] . "',
		'" . time() . "',
		'',
		'PENDING',
		'PENDING',
		'" . $birth_date . "'
		)");

		echo mysql_error();


	}


	public function user($uid){
		$sel = mysql_query("SELECT * FROM users WHERE user_ID = '" . $this->db_cmp($uid) . "'");
		$res = mysql_fetch_array($sel);

		return $res;
	}

	public function get_limit($max1 , $max2){
		$user = $this->user($_SESSION['uid']);
		if($user['user_status'] == "EMAILCONFIRMED"){ $this->limit = $max1; }
		if($user['user_status'] == "ADDRESSCONFIRMED"){ $this->limit = $max2; }

		return $this->limit;
	}


	public function get_perc($perctax_novrfy , $perctax_vrfy){
		$user = $this->user($_SESSION['uid']);
		if($user['user_status'] == "EMAILCONFIRMED"){ $this->tax = $perctax_novrfy; }
		if($user['user_status'] == "ADDRESSCONFIRMED"){ $this->tax = $perctax_vrfy; }

		return $this->tax;
	}

	public function get_exchanges_no(){
		$num = mysql_num_rows(mysql_query("SELECT exchange_ID FROM exchange WHERE exchange_user_ID = '" . $_SESSION['uid'] . "'"));
		return $num;
	}

	public function get_failed_exchanges_no(){
		$num = mysql_num_rows(mysql_query("SELECT exchange_ID FROM exchange WHERE exchange_user_ID = '" . $_SESSION['uid'] . "' AND exchange_status='FAILED'"));
		return $num;
	}

	public function get_ok_exchanges_no(){
		$num = mysql_num_rows(mysql_query("SELECT exchange_ID FROM exchange WHERE exchange_user_ID = '" . $_SESSION['uid'] . "' AND exchange_status='OK'"));
		return $num;
	}

	public function get_processing_exchanges_no(){
		$num = mysql_num_rows(mysql_query("SELECT exchange_ID FROM exchange WHERE exchange_user_ID = '" . $_SESSION['uid'] . "' AND exchange_status='PROCESSING'"));
		return $num;
	}



	public function is_exchange_duplicate($exchange_ident){
		$sel = mysql_query("SELECT exchange_ID FROM exchange WHERE exchange_ident = '$exchange_ident' AND exchange_user_ID = '" . $_SESSION['uid'] . "'");
		$res = mysql_fetch_array($sel);
		if($res['exchange_ID']){
			return true;
		}else{
			return false;
		}
	}
}
?>